package cc.yugu.yhdw.common.utils;

import cc.yugu.yhdw.common.entity.push.PushMsg;
import com.gexin.rp.sdk.base.impl.AppMessage;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.base.payload.MultiMedia;
import com.gexin.rp.sdk.base.uitls.AppConditions;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.gexin.rp.sdk.template.style.Style0;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.exceptions.RequestException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class GetuiUtils {

    private static String appId = "72IpBw0MvS9Qql88KPU4N7";
    private static String appKey = "ot3G3oedJE6pp4IZ41q3S1";
    private static String masterSecret = "pe3mSOYXJZ5Smf7w0XQ4j5";

    private static String host = "http://sdk.open.api.igexin.com/apiex.htm";

    public static boolean sendCommandMessage(String target, String content) throws IOException {
        PushMsg pushMsg = (PushMsg) YhdwUtils.decodeJson(content, PushMsg.class);
        IPushResult ref = null;
        if (pushMsg.getType() == PushMsg.Type.SINGLE.getValue()) {
            ref = pushMessageToSingle(pushMsg, target);
        } else if (pushMsg.getType() == PushMsg.Type.MANY.getValue()) {
            String[] targets = target.split(",");
            ref = pushMessageToList(pushMsg, targets);
        } else {
            ref = pushMessageToApp(pushMsg);
        }
        if (ref == null) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 单个用户发送
     *
     * @param pushMsg
     * @param CID
     * @return
     */
    private static IPushResult pushMessageToSingle(PushMsg pushMsg, String CID) {
        IGtPush push = new IGtPush(host, appKey, masterSecret);

        TransmissionTemplate template = getTemplate(pushMsg.getData());
//        NotificationTemplate template = notificationTemplateDemo(pushMsg.getData());

        SingleMessage message = new SingleMessage();
        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(2 * 3600 * 1000);

        message.setData(template);
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);

        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(CID);
        //target.setAlias(Alias);
        IPushResult ret = null;
        try {
            ret = push.pushMessageToSingle(message, target);
        } catch (RequestException e) {
            e.printStackTrace();
            ret = push.pushMessageToSingle(message, target, e.getRequestId());
        }
        return ret;
    }

    /**
     * 多个用户推送
     *
     * @param pushMsg
     * @param CidArray
     * @return
     */
    private static IPushResult pushMessageToList(PushMsg pushMsg, String[] CidArray) {
        // 配置返回每个用户返回用户状态，可选
        System.setProperty("gexin_pushList_needDetails", "true");
        // 配置返回每个别名及其对应cid的用户状态，可选
        // System.setProperty("gexin_pushList_needAliasDetails", "true");
        IGtPush push = new IGtPush(host, appKey, masterSecret);
        // 通知透传模板
        NotificationTemplate template = notificationTemplateDemo(pushMsg.getData());
        ListMessage message = new ListMessage();
        message.setData(template);
        // 设置消息离线，并设置离线时间
        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 1000 * 3600);
        // 配置推送目标
        List targets = new ArrayList();
        Target target = new Target();
        for (String CID : CidArray) {
            target.setClientId(CID);
            target.setAppId(appId);

            targets.add(target);
        }
        // taskId用于在推送时去查找对应的message
        String taskId = push.getContentId(message);
        IPushResult ret = null;
        try {
            ret = push.pushMessageToList(taskId, targets);
        } catch (RequestException e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 整个APP推送,可筛选
     *
     * @param pushMsg
     * @return
     */
    private static IPushResult pushMessageToApp(PushMsg pushMsg) {
        IGtPush push = new IGtPush(host, appKey, masterSecret);

        NotificationTemplate template = notificationTemplateDemo(pushMsg.getData());
        AppMessage message = new AppMessage();
        message.setData(template);

        message.setOffline(true);
        //离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 1000 * 3600);
        //推送给App的目标用户需要满足的条件
        AppConditions cdt = new AppConditions();
        List<String> appIdList = new ArrayList<String>();
        appIdList.add(appId);
        message.setAppIdList(appIdList);

        //手机类型
        List<String> phoneTypeList = new ArrayList<String>();
        //省份
        List<String> provinceList = new ArrayList<String>();
        //自定义tag
        List<String> tagList = new ArrayList<String>();

        cdt.addCondition(AppConditions.PHONE_TYPE, phoneTypeList);
        cdt.addCondition(AppConditions.REGION, provinceList);
        cdt.addCondition(AppConditions.TAG, tagList);
        message.setConditions(cdt);
        IPushResult ret = null;
        try {
            ret = push.pushMessageToApp(message);
        } catch (RequestException e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 通知模板
     *
     * @param data
     * @return
     */
    private static NotificationTemplate notificationTemplateDemo(PushMsg.Data data) {
        NotificationTemplate template = new NotificationTemplate();
        // 设置APPID与APPKEY
        template.setAppId(appId);
        template.setAppkey(appKey);

        Style0 style = new Style0();
        // 设置通知栏标题与内容
        style.setTitle(data.getTitle());
        style.setText(data.getText());
        // 配置通知栏图标
        style.setLogo(data.getLogo());
        // 配置通知栏网络图标
        style.setLogoUrl(data.getLogoUrl());
        // 设置通知是否响铃，震动，或者可清除
        style.setRing(true);
        style.setVibrate(true);
        style.setClearable(true);
        template.setStyle(style);

        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        template.setTransmissionType(data.getTransmissionType());
        template.setTransmissionContent(data.getTransmissionContent());
        return template;
    }

    /**
     * 透传模板
     *
     * @param data
     * @return
     */
    private static TransmissionTemplate transmissionTemplate(PushMsg.Data data) {
        TransmissionTemplate template = new TransmissionTemplate();
        // 设置APPID与APPKEY
        template.setAppId(appId);
        template.setAppkey(appKey);

        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        template.setTransmissionType(data.getTransmissionType());
        template.setTransmissionContent(data.getTransmissionContent());
        return template;
    }

    /**
     * IOS透传模板
     * @return
     */
    public static TransmissionTemplate getTemplate(PushMsg.Data data) {
        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);

        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        template.setTransmissionContent(data.getTransmissionContent());
        template.setTransmissionType(data.getTransmissionType());

        APNPayload payload = new APNPayload();
        //在已有数字基础上加1显示，设置为-1时，在已有数字上减1显示，设置为数字时，显示指定数字
        payload.setAutoBadge("+1");
        payload.setContentAvailable(1);
        payload.setSound("default");
        payload.setCategory("$由客户端定义");

        //简单模式APNPayload.SimpleMsg
        payload.setAlertMsg(new APNPayload.SimpleAlertMsg("hello"));

        //字典模式使用APNPayload.DictionaryAlertMsg
        //payload.setAlertMsg(getDictionaryAlertMsg());

        // 添加多媒体资源
        payload.addMultiMedia(new MultiMedia().setResType(MultiMedia.MediaType.video)
                .setResUrl("http://ol5mrj259.bkt.clouddn.com/test2.mp4")
                .setOnlyWifi(true));

        template.setAPNInfo(payload);
        return template;
    }
    private static APNPayload.DictionaryAlertMsg getDictionaryAlertMsg(){
        APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
        alertMsg.setBody("body");
        alertMsg.setActionLocKey("ActionLockey");
        alertMsg.setLocKey("LocKey");
        alertMsg.addLocArg("loc-args");
        alertMsg.setLaunchImage("launch-image");
        // iOS8.2以上版本支持
        alertMsg.setTitle("Title");
        alertMsg.setTitleLocKey("TitleLocKey");
        alertMsg.addTitleLocArg("TitleLocArg");
        return alertMsg;
    }
}
